﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace WcfServiceParsingSite
{
    public class ServParsSite : IServParsSite, IDisposable
    {
        private SqlConnection _conn;
        private string PATH;
        private long CHUNK_LENGTH;

        public ServParsSite() 
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ProductsDBConnectionString"].ConnectionString;
            _conn = new SqlConnection(connectionString);
            _conn.Open();
            PATH = ConfigurationManager.AppSettings["PATH"];
            CHUNK_LENGTH = Convert.ToInt64(ConfigurationManager.AppSettings["CHUNK_LENGTH"]);
            //TestUpdServ();
        }

        public void Dispose()
        {
            if (_conn.State == ConnectionState.Open)
                _conn.Close();
        }

        //private void CloseConnect()
        //{
        //    if (_conn.State == ConnectionState.Open)
        //        _conn.Close();
        //}

        //private void OpenConnect()
        //{
        //    if (_conn.State == ConnectionState.Closed)
        //        _conn.Open();
        //}

        public int NewClient(string ip, string comment, DataTable files, int pharmCode, string windowsInfo)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_NewClient";
            command.CommandTimeout = 30;
            command.Parameters.AddWithValue("@ip", ip);
            command.Parameters.AddWithValue("@comment", comment);
            command.Parameters.AddWithValue("@files", files);
            command.Parameters.AddWithValue("@pharmcode", pharmCode);
            command.Parameters.AddWithValue("@windowsinfo", windowsInfo);
            return Convert.ToInt32(command.ExecuteScalar());
        }

        public void ClientPharmCodeUpd(int clientid, int pharmCode)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_ClientPharmCodeUpd";
            command.CommandTimeout = 30;
            command.Parameters.AddWithValue("@parmcode", pharmCode);
            command.Parameters.AddWithValue("@clientid", clientid);
            command.ExecuteNonQuery();
        }

        public void ClientWinInfoUpd(int clientid, string windowsInfo)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_ClientWinInfoUpd";
            command.CommandTimeout = 30;
            command.Parameters.AddWithValue("@windowsinfo", windowsInfo);
            command.Parameters.AddWithValue("@clientid", clientid);
            command.ExecuteNonQuery();
        }

        public WorkPlanStr IAmFree(int clientid)
        {
            WorkPlanStr wps = new WorkPlanStr();
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_IAmFree";
            command.CommandTimeout = 30;
            command.Parameters.AddWithValue("@clientid", clientid);
            DataTable dt = new DataTable();
            dt.Load(command.ExecuteReader());

            //SqlDataReader dataReader = command.ExecuteReader();
            //using (dataReader)
            //{
            //    if (dataReader.Read())
            //    {
            //        wps.UrlPath = dataReader.GetValue(0).ToString();
            //        wps.UrlParam = dataReader.GetValue(1).ToString();
            //        wps.Drug = dataReader.GetValue(2).ToString();
            //        wps.WorkPlanStrID = Convert.ToInt32(dataReader.GetValue(3));
            //        wps.WebSiteID = Convert.ToInt32(dataReader.GetValue(4));
            //    }
            //}
            if (dt.Rows.Count == 1)
            {
                wps.UrlPath = dt.Rows[0][0].ToString();
                wps.UrlParam = dt.Rows[0][1].ToString();
                wps.Drug = dt.Rows[0][2].ToString();
                wps.WorkPlanStrID = Convert.ToInt32(dt.Rows[0][3]);
                wps.WebSiteID = Convert.ToInt32(dt.Rows[0][4]);
            }

            return wps;
        }

        public void CompPriceIns(DataTable comprice, int wpstrid, int clientid)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_CompPriceIns";
            command.CommandTimeout = 30;
            command.Parameters.AddWithValue("@comprice", comprice);
            command.Parameters.AddWithValue("@wpstrid", wpstrid);
            command.Parameters.AddWithValue("@clientid", clientid);
            command.ExecuteNonQuery();
        }

        public void ClientIPUpd(int clientid, string newip)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_ClientIPUpd";
            command.CommandTimeout = 30;
            command.Parameters.AddWithValue("@newip", newip);
            command.Parameters.AddWithValue("@clientid", clientid);
            command.ExecuteNonQuery();
        }

        public FileNameVersion GetInstallerInfo()
        {
            FileNameVersion fnv = new FileNameVersion();
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_GetInstallerInfo";
            command.CommandTimeout = 30;
            SqlDataReader dataReader = command.ExecuteReader();
            using (dataReader)
            {
                if (dataReader.Read())
                {
                    fnv.Fileid = Convert.ToInt32(dataReader.GetValue(0));
                    fnv.FileName = dataReader.GetValue(1).ToString();
                    fnv.FileVersion = dataReader.GetValue(3).ToString();
                }
            }

            return fnv;
        }

        public FileNameVersion GetWinServiceInfo()
        {
            FileNameVersion fnv = new FileNameVersion();
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_GetWinServiceInfo";
            command.CommandTimeout = 30;
            SqlDataReader dataReader = command.ExecuteReader();
            using (dataReader)
            {
                if (dataReader.Read())
                {
                    fnv.Fileid = Convert.ToInt32(dataReader.GetValue(0));
                    fnv.FileName = dataReader.GetValue(1).ToString();
                    fnv.FileVersion = dataReader.GetValue(3).ToString();
                }
            }

            return fnv;
        }

        public void ClientFileVersionUpd(int clientid, string falename, string fileversion)
        {
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_ClientFileVersionUpd";
            command.CommandTimeout = 30;
            command.Parameters.AddWithValue("@clientid", clientid);
            command.Parameters.AddWithValue("@falename", falename);
            command.Parameters.AddWithValue("@fileversion", fileversion);
            command.ExecuteNonQuery();
        }
        //*******передача файлов**********///
        public string[] GetFilesNames()
        {
            var result = Directory.GetFiles(PATH);
            for (var i = 0; i < result.Length; i++)
                result[i] = Path.GetFileName(result[i]);
            return result;
        }

        public int GetFileChunksCount(string name)
        {
            return (int)Math.Ceiling(new FileInfo(PATH + name).Length / (double)CHUNK_LENGTH);
        }

        public string GetFileChunk(string name, int chunkNumber)
        {
            var stream = File.OpenRead(PATH + name);
            var fileLenght = new FileInfo(PATH + name).Length;
            byte[] chunk = new byte[(int)Math.Min(CHUNK_LENGTH, fileLenght - chunkNumber * CHUNK_LENGTH)];
            stream.Position = chunkNumber * CHUNK_LENGTH;
            stream.Read(chunk, 0, chunk.Length);
            return Convert.ToBase64String(chunk);
        }

        public void TestUpdServ()
        {
            SqlCommand command = new SqlCommand();
            command.Connection = _conn;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "wcf_test";
            command.ExecuteNonQuery();
        }
    }
}
